// 多语言国际化系统 - 支持10种语言
class I18n {
    constructor() {
        this.currentLanguage = 'zh';
        this.languages = {
            'zh': '中文',
            'en': 'English', 
            'ja': '日本語',
            'ko': '한국어',
            'fr': 'Français',
            'de': 'Deutsch',
            'es': 'Español',
            'ru': 'Русский',
            'ar': 'العربية',
            'pt': 'Português'
        };
        this.translations = {};
        this.init();
    }

    init() {
        // 从localStorage加载语言设置
        const savedLang = localStorage.getItem('timeecho_language');
        if (savedLang && Object.keys(this.languages).includes(savedLang)) {
            this.currentLanguage = savedLang;
        }

        // 加载翻译数据
        this.loadTranslations();
        
        // 绑定语言切换事件
        this.bindEvents();
        
        // 初始化页面文本
        this.updatePageText();
    }

    loadTranslations() {
        // 使用全局多语言翻译数据
        if (window.multiLanguageTranslations) {
            this.translations = window.multiLanguageTranslations;
        } else {
            // 回退到基础翻译
            this.translations = {
                zh: {
                    title: "时空回音",
                    subtitle: "Time Echo",
                    newGame: "开始新游戏",
                    continue: "继续游戏",
                    achievements: "成就",
                    timeline: "时间线",
                    settings: "设置",
                    menu: "菜单",
                    save: "保存",
                    chapter: "章节",
                    loading: "加载中...",
                    back: "返回"
                },
                en: {
                    title: "Time Echo",
                    subtitle: "时空回音",
                    newGame: "New Game",
                    continue: "Continue",
                    achievements: "Achievements",
                    timeline: "Timeline",
                    settings: "Settings",
                    menu: "Menu",
                    save: "Save",
                    chapter: "Chapter",
                    loading: "Loading...",
                    back: "Back"
                }
            };
        }
    }

    bindEvents() {
        const langToggle = document.getElementById('langToggle');
        if (langToggle) {
            langToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                this.showLanguageSelector();
            });
        }
        
        // 点击页面其他地方关闭语言选择器
        document.addEventListener('click', (e) => {
            const selector = document.getElementById('languageSelector');
            if (selector && !selector.contains(e.target)) {
                this.hideLanguageSelector();
            }
        });
    }

    showLanguageSelector() {
        // 移除已存在的选择器
        this.hideLanguageSelector();
        
        // 创建语言选择器
        const selector = document.createElement('div');
        selector.id = 'languageSelector';
        selector.className = 'language-selector';
        
        const langToggle = document.getElementById('langToggle');
        const rect = langToggle.getBoundingClientRect();
        
        selector.style.position = 'fixed';
        selector.style.top = (rect.bottom + 10) + 'px';
        selector.style.right = '20px';
        selector.style.zIndex = '10000';
        
        // 创建语言选项
        Object.entries(this.languages).forEach(([code, name]) => {
            const option = document.createElement('div');
            option.className = 'language-option';
            if (code === this.currentLanguage) {
                option.classList.add('active');
            }
            
            option.innerHTML = `
                <span class="lang-code">${code.toUpperCase()}</span>
                <span class="lang-name">${name}</span>
            `;
            
            option.addEventListener('click', () => {
                this.switchLanguage(code);
                this.hideLanguageSelector();
            });
            
            selector.appendChild(option);
        });
        
        document.body.appendChild(selector);
        
        // 添加动画
        setTimeout(() => {
            selector.classList.add('show');
        }, 10);
    }

    hideLanguageSelector() {
        const selector = document.getElementById('languageSelector');
        if (selector) {
            selector.remove();
        }
    }

    switchLanguage(langCode) {
        if (this.languages[langCode]) {
            this.currentLanguage = langCode;
            localStorage.setItem('timeecho_language', this.currentLanguage);
            this.updatePageText();
            this.updateLanguageButton();
            
            // 触发语言切换事件
            window.dispatchEvent(new CustomEvent('languageChanged', {
                detail: { language: this.currentLanguage }
            }));
            
            console.log(`🌐 语言已切换至: ${this.languages[langCode]}`);
        }
    }

    toggleLanguage() {
        // 保留此方法以兼容旧代码
        this.showLanguageSelector();
    }

    updateLanguageButton() {
        const langToggle = document.getElementById('langToggle');
        if (langToggle) {
            langToggle.innerHTML = `
                <span class="current-lang">${this.currentLanguage.toUpperCase()}</span>
                <span class="dropdown-arrow">▼</span>
            `;
        }
    }

    updatePageText() {
        // 更新所有带有 data-i18n 属性的元素
        const elements = document.querySelectorAll('[data-i18n]');
        elements.forEach(element => {
            const key = element.getAttribute('data-i18n');
            const translation = this.get(key);
            if (translation) {
                element.textContent = translation;
            }
        });

        // 更新语言按钮
        this.updateLanguageButton();
    }

    get(key) {
        const keys = key.split('.');
        let value = this.translations[this.currentLanguage];
        
        for (const k of keys) {
            if (value && value.hasOwnProperty(k)) {
                value = value[k];
            } else {
                // 如果当前语言没有找到，尝试回退到中文
                value = this.translations['zh'];
                for (const fallbackKey of keys) {
                    if (value && value.hasOwnProperty(fallbackKey)) {
                        value = value[fallbackKey];
                    } else {
                        console.warn(`Translation key not found: ${key}`);
                        return key; // 返回key作为fallback
                    }
                }
                break;
            }
        }
        
        return value || key;
    }

    getCurrentLanguage() {
        return this.currentLanguage;
    }

    // 格式化文本，支持变量替换
    format(key, variables = {}) {
        let text = this.get(key);
        
        // 替换变量 {variable}
        Object.keys(variables).forEach(variable => {
            const regex = new RegExp(`{${variable}}`, 'g');
            text = text.replace(regex, variables[variable]);
        });
        
        return text;
    }

    // 动态更新元素文本
    updateElement(element, key, variables = {}) {
        if (typeof element === 'string') {
            element = document.querySelector(element);
        }
        
        if (element) {
            element.textContent = this.format(key, variables);
        }
    }

    // 添加新的翻译
    addTranslations(language, translations) {
        if (!this.translations[language]) {
            this.translations[language] = {};
        }
        
        Object.assign(this.translations[language], translations);
    }
}

// 创建全局实例
window.i18n = new I18n();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.i18n.updatePageText();
});

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = I18n;
}